<template>
  <div class="article-manager">
    <el-card :bordered="false" shadow="never" class="ivu-mt" :body-style="{ padding: 0 }">
      <div class="padding-add">
        <el-form ref="artFrom" :model="artFrom" label-width="80px" label-position="right" inline @submit.native.prevent>
          <el-form-item label="菜品分类：" label-for="pid">
            <el-select v-model="artFrom.dishes_category_id" clearable placeholder="请选择">
              <el-option
                v-for="item in categoryList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="菜品搜索：" label-for="store_name">
            <el-input
              clearable
              placeholder="请输入商品名称/关键字/ID"
              v-model="artFrom.name"
              class="form_content_width"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getDataList">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card :body-style="{padding: '20px 20px 20px'}" :bordered="false" class="ivu-mt mt16" shadow="never">
      <div class="Button">
        <el-button type="primary" class="mr14" @click="dialogVisible = true">添加菜品</el-button>
      </div>

      <el-table
        ref="table"
        v-loading="loading"
        :data="tableList"
        :row-key="getRowKey"
        class="ivu-mt mt14"
        empty-text="暂无数据"
        highlight-current-row
      >
        <el-table-column label="分类ID" width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.id }}</span>
          </template>
        </el-table-column>

        <el-table-column label="菜品图片" min-width="90">
          <template slot-scope="scope">
            <div class="tabBox_img" v-viewer>
              <img v-lazy="scope.row.dishes_img" />
            </div>
          </template>
        </el-table-column>

        <el-table-column label="菜品名称">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>

        <el-table-column label="菜品分类">
          <template slot-scope="scope">
            <span>{{ scope.row.category.name }}</span>
          </template>
        </el-table-column>

        <el-table-column label="菜品价格">
          <template slot-scope="scope">
            <span>{{ scope.row.normal_price }}</span>
          </template>
        </el-table-column>


        <el-table-column label="是否显示" min-width="100">
          <template slot-scope="scope">
            <el-switch
              class="defineSwitch"
              :active-value="1"
              :inactive-value="0"
              v-model="scope.row.is_show"
              :value="scope.row.is_show"
              size="large"
              active-text="显示"
              inactive-text="不显示"
              @change="handleChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作" fixed="right" minWidth="100">
          <template slot-scope="scope">
            <a @click="handleEdit(scope.row)">编辑</a>
            <el-divider direction="vertical"></el-divider>
            <a @click="handleDelete(scope.row.id)">删除</a>
          </template>
        </el-table-column>

      </el-table>
      <div class="acea-row row-right page">
        <pagination
          v-if="total"
          :total="total"
          :page.sync="artFrom.page"
          :limit.sync="artFrom.limit"
          @pagination="getDataList"
        />
      </div>
    </el-card>

    <el-dialog
      title="添加菜品"
      :visible.sync="dialogVisible"
      width="50%"
      @close="cancel"
      :close-on-click-modal="false"
    >
      <el-form
        class="formValidate mt20"
        ref="formValidate"
        :rules="ruleValidate"
        :model="formValidate"
        @submit.native.prevent
      >
        <el-col :span="24">
          <el-form-item label="菜品分类：" prop="dishes_category_id">
            <el-select v-model="formValidate.dishes_category_id" clearable placeholder="请选择">
              <el-option
                v-for="item in categoryList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="菜品名称：" prop="name">
            <el-input class="content_width" v-model.trim="formValidate.name" placeholder="请输入菜品名称" />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-col :span="24">
            <el-form-item label="菜品主图750*750" prop="dishes_img">
              <div class="picBox" @click="modalPicTap('dan', 'danFrom')">
                <div class="pictrue" v-if="formValidate.dishes_img">
                  <img v-lazy="formValidate.dishes_img" />
                </div>
                <div class="upLoad acea-row row-center-wrapper" v-else>
                  <i class="el-icon-picture-outline" style="font-size: 24px"></i>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-col>

        <el-col :span="24">
          <el-form-item label="菜品价格：" prop="normal_price">
            <el-input-number v-model="formValidate.normal_price" :min="1" :max="10000" :precision="2" :step="1"></el-input-number>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="VIP价格：" prop="vip_price">
            <el-input-number v-model="formValidate.vip_price" :min="1" :max="10000" :precision="2" :step="1"></el-input-number>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="是否显示：" prop="is_show">
            <el-switch
              class="defineSwitch"
              :active-value="1"
              :inactive-value="0"
              v-model="formValidate.is_show"
              :value="formValidate.is_show"
              size="large"
              active-text="显示"
              inactive-text="不显示"
            >
            </el-switch>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="内容：">
            <WangEditor
              style="width: 100%;"
              :content="formValidate.dishes_content"
              @editorContent="getEditorContent"
            ></WangEditor>
          </el-form-item>
        </el-col>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitAdd">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 上传图片-->
    <el-dialog :visible.sync="modalPic" width="950px" title="上传商品图" :close-on-click-modal="false">
      <uploadPictures
        :isChoice="isChoice"
        @getPic="getPic"
        @getPicD="getPicD"
        :gridBtn="gridBtn"
        :gridPic="gridPic"
        v-if="modalPic"
      ></uploadPictures>
    </el-dialog>
  </div>
</template>

<script>
import { categoryList, getDishesList, addDishes, deleteDishes, editDishes, changeDishes } from "@api/dishes";
import UploadPictures from "@/components/uploadPictures";
import WangEditor from "@/components/wangEditor/index.vue";

export default {
  name: "index",
  components: {
    UploadPictures,
    WangEditor
  },
  data() {
    return {
      tableList: [],
      loading: false,
      total: 0,
      artFrom: {
        page: 1,
        limit: 15,
        dishes_category_id: "",
        is_show: 1,
        name: ""
      },
      categoryList: [],
      dialogVisible: false,
      ruleValidate: {
        dishes_category_id: [{ required: true, message: '请选择菜品分类', trigger: 'change' }],
        name: [{ required: true, message: '请输入菜品名称', trigger: 'blur' }],
        dishes_img: [{ required: true, message: '请选择菜品主图', trigger: 'change' }],
      },
      formValidate: {
        dishes_category_id: "",
        name: "",
        dishes_img: "",
        dishes_detail: "",
        normal_price: "",
        vip_price: "",
        is_show: 1,
        dishes_content: ''
      },
      modalPic: false,
      isChoice: '',
      gridPic: {
        xl: 6,
        lg: 8,
        md: 12,
        sm: 12,
        xs: 12,
      },
      gridBtn: {
        xl: 4,
        lg: 8,
        md: 8,
        sm: 8,
        xs: 8,
      },
    };
  },
  methods: {
    getCategoryList() {
      categoryList().then(res => {
        this.categoryList = res.data.data;
      });
    },
    getDataList() {
      this.loading = true;
      getDishesList(this.artFrom).then(res => {
        this.loading = false;
        this.tableList = res.data.data;
        this.total = res.data.count;
      });
    },
    getRowKey(row) {
      return row.id;
    },
    cancel() {
      this.$refs.formValidate.resetFields()
      this.dialogVisible = false
    },
    // 获取单张图片信息
    getPic(pc) {
      switch (this.picTit) {
        case 'danFrom':
          this.formValidate.dishes_img = pc.att_dir;
          break;
        default:
          if (!!this.formValidate.dishes_img && this.formValidate.dishes_img.length) {
            this.$set(this.specsData[this.tableIndex], '_checked', true);
          }
          this.specsData[this.tableIndex].pic = pc.att_dir;
      }
      this.modalPic = false;
    },
    // 获取多张图信息
    getPicD(pc) {
      this.images = pc;
      this.images.map((item) => {
        this.formValidate.dishes_img.push(item.att_dir);
        this.formValidate.dishes_img = this.formValidate.dishes_img.splice(0, 10);
      });
      this.modalPic = false;
    },
    handleDragStart(e, item) {
      this.dragging = item;
    },
    handleDragEnd(e, item) {
      this.dragging = null;
    },
    // 首先把div变成可以放置的元素，即重写dragenter/dragover
    handleDragOver(e) {
      e.dataTransfer.dropEffect = 'move'; // e.dataTransfer.dropEffect="move";//在dragenter中针对放置目标来设置!
    },
    handleDragEnter(e, item) {
      e.dataTransfer.effectAllowed = 'move'; // 为需要移动的元素设置dragstart事件
      if (item === this.dragging) {
        return;
      }
      const newItems = [...this.formValidate.dishes_img];
      const src = newItems.indexOf(this.dragging);
      const dst = newItems.indexOf(item);
      newItems.splice(dst, 0, ...newItems.splice(src, 1));
      this.formValidate.dishes_img = newItems;
    },
    handleRemove(i) {
      this.images.splice(i, 1);
      this.formValidate.dishes_img.splice(i, 1);
    },
    modalPicTap(tit, picTit, index) {
      console.log('modalPicTap');
      this.modalPic = true;
      this.isChoice = tit === 'dan' ? '单选' : '多选';
      this.picTit = picTit;
      this.tableIndex = index;
    },
    getEditorContent(data) {
      this.formValidate.dishes_content = data;
    },
    submitAdd() {
      this.$refs['formValidate'].validate((valid) => {
        if (valid) {
          if(!this.formValidate.id) {
            addDishes(this.formValidate).then(res => {
              this.$message({
                type: "success",
                message: "菜品添加成功"
              });
              this.$refs.formValidate.resetFields()
              this.dialogVisible = false
            }).catch(err => {
              this.$message({
                type: "error",
                message: "菜品添加失败"
              });
            })
          } else {
            editDishes(this.formValidate).then(res => {
              this.$message({
                type: "success",
                message: "菜品修改成功"
              });
              this.$refs.formValidate.resetFields()
              this.dialogVisible = false
            }).catch(err => {
              this.$message({
                type: "error",
                message: "菜品修改失败"
              });
            })
            this.getDataList()
          }

        } else {
          return false;
        }
      });
    },
    // 删除
    handleDelete(id) {
      this.$confirm("此操作将永久删除该菜品, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deleteDishes(id).then(() => {
          this.$message({
            type: "success",
            message: "菜品删除成功"
          });
          this.getDataList()
        }).catch(() => {
          this.$message({
            type: "error",
            message: "菜品删除失败"
          });
        })
      }).catch();
    },
    handleEdit(row) {
      this.formValidate = row
      this.dialogVisible = true
    },
    handleChange(row) {
      changeDishes(row.id, row.is_show).then(() => {
        this.$message({
          type: "success",
          message: "修改成功"
        });
        this.getDataList()
      }).catch(() => {
        this.$message({
          type: "error",
          message: "修改失败"
        });
      })
    }
  },
  created() {
    this.getCategoryList();
    this.getDataList();
  }
};
</script>

<style lang="scss" scoped>
  .picBox {
    display: inline-block;
    cursor: pointer;
  }

  .pictrue {
    width: 60px;
    height: 60px;
    border: 1px dotted rgba(0, 0, 0, 0.1);
    margin-right: 15px;
    display: inline-block;
    position: relative;
    cursor: pointer;

    img {
      width: 100%;
      height: 100%;
    }

    .btndel {
      position: absolute;
      z-index: 9;
      width: 20px !important;
      height: 20px !important;
      left: 46px;
      top: -4px;
    }
  }

  .upLoad {
    width: 58px;
    height: 58px;
    line-height: 58px;
    border: 1px dotted rgba(0, 0, 0, 0.1);
    border-radius: 4px;
    background: rgba(0, 0, 0, 0.02);
    cursor: pointer;
  }

  ::v-deep .w-e-text-container {
    height: 300px !important;
  }
</style>
